<template>
  <el-dialog
    v-model="visible"
    title="解绑用户"
    width="500px"
    @close="resetForm"
  >
    <el-form ref="userFormRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="解绑原因" prop="reason">
        <el-input
          v-model="form.reason"
          type="textarea"
          placeholder="请输入解绑原因"
          :autosize="{ minRows: 4, maxRows: 6 }"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button :loading="submitLoading" type="primary" @click="submitForm"
        >确认</el-button
      >
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { unbindTelegramUser } from "@/api/adminTelegramApi";
import { message } from "@/utils/message";

interface UserForm {
  reason: string;
}
const userId = ref(0);

const visible = ref(false);

const form = reactive<UserForm>({
  reason: ""
});

const emits = defineEmits(["refresh"]);

const rules: FormRules = {
  reason: [{ required: true, message: "请输入解绑原因", trigger: "blur" }]
};

const userFormRef = ref<FormInstance>();
const submitLoading = ref(false);
const submitForm = () => {
  userFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        submitLoading.value = true;
        console.log(userId.value, form);
        await unbindTelegramUser(userId.value, form);
        message("解绑成功", { type: "success" });
        visible.value = false;
        emits("refresh");
      } catch (error) {
        console.error(error);
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

const resetForm = () => {
  userFormRef.value?.resetFields();
};
const open = (id: number, status: boolean) => {
  userId.value = id;
  visible.value = true;
};

defineExpose({ open });
</script>
